﻿using Microsoft.Extensions.Options;
using Minio;
using Naruto.FileStorage.Abstractions;
using Naruto.FileStorage.Helper;

namespace Naruto.FileStorage.Provider.MinIO
{
    /// <summary>
    /// 
    /// </summary>
    public class MinIOFileStorage : IFileStorage
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly MinioClient _minioClient;

        /// <summary>
        /// 
        /// </summary>
        private readonly MinIOOption _minIOOption;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="minioClient"></param>
        public MinIOFileStorage(IOptions<MinIOOption> options)
        {
            var minClient = new MinioClient(options.Value.ServerUrl, options.Value.Key, options.Value.Secret);
            _minioClient = options.Value.IsSSL ? minClient.WithSSL() : minClient;
            _minIOOption = options.Value;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task<string> AddFileAsync(Stream fileStream, string fileName)
        {
            //判断当前文件是否有效
            if (fileStream == null || !fileStream.CanRead || fileStream.Length <= 0)
            {
                return default;
            }

            //var fileNameSplit = fileName.SplitFileName();
            //if (fileNameSplit == null)
            //{
            //    return default;
            //}
            //fileStream.Position = 0;
            await _minioClient.PutObjectAsync(_minIOOption.BucketName, fileName, fileStream, fileStream.Length);
            return fileName;
        }

        public async Task DeleteFileAsync(string fileName)
        {
            await _minioClient.RemoveObjectAsync(_minIOOption.BucketName, fileName);
        }

        public async Task<byte[]> GetFileAsync(string fileName)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                await _minioClient.GetObjectAsync(_minIOOption.BucketName, fileName, async (stream) => await stream.CopyToAsync(memoryStream));
                var bytes = new byte[memoryStream.Length];
                await memoryStream.ReadAsync(bytes, 0, bytes.Length);
                return bytes;
            }
        }
    }
}